package org.ttitfly.workflow.engine.persistence.hibernate;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.ttitfly.workflow.engine.persistence.PersistenceException;
import org.ttitfly.workflow.engine.persistence.PersistenceService;
import org.ttitfly.workflow.engine.run.ProcessInstance;
import org.ttitfly.workflow.engine.run.Task;

@Component("hibernatePersistenceService")
public class HibernatePersistenceService implements PersistenceService {
	
	@Resource
	private HibernateTaskDao taskDao;
	
	@Resource
	private HibernateProcessInstanceDao processInstanceDao;

	@Override
	public Task getTask(int id) throws PersistenceException {
		return taskDao.get(id);
	}

	@Override
	public void save(ProcessInstance processInstance)
			throws PersistenceException {
		processInstanceDao.save(processInstance);
	}

	@Override
	public void save(Task task) throws PersistenceException {
		if (StringUtils.isNotBlank(task.getAssigners())) {
			task.setAssigners("," + task.getAssigners() + ",");
		}
		taskDao.save(task);
	}

	@Override
	public void update(ProcessInstance processInstance)
			throws PersistenceException {
		processInstanceDao.save(processInstance);
	}

	@Override
	public void update(Task task) throws PersistenceException {
		taskDao.save(task);
	}

	@Override
	public int countTask(String principal, String processName, String activityName, int processInstanceId, int[] status) {
		return taskDao.count(principal, processName, activityName, processInstanceId, status);
	}

	@Override
	public List<Task> findTask(String principal, String processName, String activityName, int processInstanceId, int[] status, int start, int count) {
		return taskDao.find(principal, processName, activityName, processInstanceId, status, start, count);
	}

	@Override
	public void deleteProcessInstance(int id) throws PersistenceException {
		processInstanceDao.delete(id);
	}

}
